/**
 * Created by xlt on 2017/6/7.
 */
import React, {PropTypes} from "react";
import {connect} from "react-redux";
import {fetchPosts, reset} from "../../actions";
import ReactDOM from "react-dom";
import {Color} from "../../utils/baseColor";
import cookie from "react-cookie";
import Notifications, {notify} from "react-notify-toast";

class login extends React.Component {
    //1.确认加入叮叮来钱 /pay/login?staffType=4&openId=oeOEswzsn33bPXIimZmevRRxTx13E&relevancePhone=13870657847&shopNo=YS20170600021
    //2.确认加入店铺  /pay/login?openId=hgsdhfshdgfhasd&shopNo=021501212&shopName=1号店&relevancePhone=15268172119;
    constructor(props) {
        super(props);
        this.state = {
            countDown: 60,
            showSendButton: "",
            showTimeButton: "none",
            timeText: "重新发送(60)",
            intervalId: 0,
            staffType: 0,
            relevancePhone: "",
            bgColor: "#9e9e9e",
            shopNo: 0,
            shopName: "",
            deleteDisPlay: "",
            userType: 0
        }
    }

    componentWillMount() {
        document.body.style.background = Color.BACKGROUND_COLOR;
        const query = this.props.location.query;
        if (query.openId) {
            cookie.save("openId", query.openId);
        }
        if (query.staffType == 4) {
            document.title = "确认加入叮叮来钱";
        } else {
            document.title = "确认加入店铺";
        }
    }

    componentDidMount() {
        const query = this.props.location.query;
        this.setState({
            relevancePhone: query.relevancePhone,
            shopNo: query.shopNo,
            shopName: query.shopName,
            staffType: query.staffType
        });
    }

    componentWillUnmount() {
        clearInterval(this.state.intervalId);
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.ValidateCode.errorCode == 0) {
            this.setState({
                showSendButton: "none",
                showTimeButton: ""
            });
        }
        // alert("发送状态:" + nextProps.ValidateCode.errorCode+"信息" + nextProps.ValidateCode.errorMessage);
        if (nextProps.VerificationCode.errorCode == 0) {
            if (this.state.staffType == 4) {
                let myColor = {background: '#0E1717', text: "#FFFFFF"};
                notify.show("登录成功", "custom", 800, myColor);
                setTimeout(function () {
                    window.location.href = "/#/pay/merchantService";
                }.bind(this), 1100);
            } else {
                window.location.href = "/#/pay/joinStoreSuccess?userType=" + nextProps.VerificationCode.data.userType + "&shopName=" + this.state.shopName + "&userName=" + nextProps.VerificationCode.data.userName;
            }
        } else if (nextProps.VerificationCode.errorCode == -1) {
            alert("您的网速较慢，请重新登录！");
        }
        else {
            this.setState({isLogin: false});
        }
        // alert("验证状态:" + nextProps.VerificationCode.errorCode + ";" + nextProps.VerificationCode.errorMessage);
    }

    sendCode() {
        let phone = ReactDOM.findDOMNode(this.refs.phoneNumber).value;
        if (phone == "") {
            alert("请输入手机号码");
            return;
        }
        if (!(/^1(3|4|5|7|8)\d{9}$/.test(phone))) {
            alert("手机号码有误，请重填");
            return;
        }
        this.handleClick();
        const header = {"X-Client-ID": "123456"};
        this.props.dispatch(reset("verificationCode"));
        this.props.dispatch(reset("sendValidateCodeToPhone"));
        this.props.dispatch(fetchPosts("sendValidateCodeToPhone", header, {phoneNumber: phone}));
    }

    handleClick() {
        let timer = setInterval(function () {
            let countDown = this.state.countDown;
            countDown--;
            if (countDown < 1) {
                this.setState({
                    timeText: "重新发送(60)",
                    showSendButton: "",
                    showTimeButton: "none",
                    countDown: 60
                });
                clearInterval(this.state.intervalId);
            } else {
                this.setState({
                    timeText: "重新发送(" + countDown + ")",
                    showSendButton: "none",
                    showTimeButton: "",
                    countDown: countDown
                });
            }
        }.bind(this), 1000);

        this.setState({
            intervalId: timer
        })
    }

    verification() {
        if (this.state.isLogin) {
            return;
        }
        let phone = ReactDOM.findDOMNode(this.refs.phoneNumber).value;
        let code = ReactDOM.findDOMNode(this.refs.codeNumber).value;
        this.setState({isLogin: true, bgColor: "#9e9e9e"});
        if (code.length == 4 && phone.length > 0) {
            const header = {"X-Client-ID": "123456"};
            this.props.dispatch(reset("sendValidateCodeToPhone"));
            this.props.dispatch(fetchPosts("verificationCode", header, {
                contactPhone: phone,
                shopNo: this.state.shopNo,
                validateCode: code,
                openId: cookie.load("openId")
            }));
        }
    }

    pageDisplay() {
        if (this.state.staffType != 4) {
            return (
                <div>
                    <p><span>{this.state.shopName}</span>邀请您加入，请您确认</p>
                </div>
            )
        }
    }

    displayDownSentence() {
        if (this.state.staffType == 4) {
            return (
                <div className="confirm-prompt-again">若手机号有误，请与业务员联系！</div>
            )
        } else {
            return (
                <div className="confirm-prompt-again">若手机号有误，请与管理者联系！</div>
            )
        }
    }

    render() {
        return (
            <div>
                <Notifications/>
                <div className="restaurant-name">
                    {this.pageDisplay()}
                </div>
                <div className="login-text">
                    <div className="login-one--rows">
                        <div className="phone-number-verification-one">
                            <div>手机号码:</div>
                            <div>
                                <input type="text" className="text-border-display" name="phoneNumber"
                                       maxLength="11"
                                       value={this.state.relevancePhone}
                                       readOnly="readOnly"
                                       onChange={this.onChangeColor.bind(this)}
                                       ref="phoneNumber"/>
                            </div>
                            <div className="login-verification-div">
                                <div name="sendCode"
                                     onClick={this.sendCode.bind(this)}
                                     style={{display: this.state.showSendButton}} className="login-verification">获取验证码
                                </div>
                                <div name="nextTime"
                                     style={{display: this.state.showTimeButton}}
                                     className="login-verification-again">{this.state.timeText}</div>
                            </div>
                        </div>
                    </div>
                    <div className="login-two-rows">
                        <div className="phone-number-verification-two">
                            <div>验证码：</div>
                            <input type="text" className="text-border-display" name="codeNumber"
                                   onChange={this.onChangeColor.bind(this)}
                                   maxLength="4"
                                   ref="codeNumber"/>
                            {/*<div className="delete-img-name" ref="deleteCode" name="deleteCode" onClick={this.deleteCode.bind(this)}*/}
                            {/*style={{display: this.state.deleteDisPlay}}>*/}
                            {/*</div>*/}
                        </div>
                    </div>
                </div>
                <div className="confirm-btn-div">
                    <button className="confirm-btn"
                            onClick={this.verification.bind(this)}
                            style={{background: this.state.bgColor}}>
                        确定
                    </button>
                </div>
                {this.displayDownSentence()}
            </div>
        );
    }

    onChangeColor() {
        let phone = ReactDOM.findDOMNode(this.refs.phoneNumber).value;
        let code = ReactDOM.findDOMNode(this.refs.codeNumber).value;
        if (code.length == 4 && phone.length > 0) {
            this.setState({bgColor: "#f6a623"});
        } else {
            this.setState({bgColor: "#9e9e9e"});
        }
        if (code.length > 0) {
            this.setState({deleteDisPlay: ""});
        } else {
            this.setState({deleteDisPlay: "none"});
        }
    }

    // deleteCode(){
    //     ReactDOM.findDOMNode(this.refs.codeNumber).value = "";
    //     this.setState({deleteDisPlay:"none"});
    // }
    // onBlurCodeNumber(){
    //     if (ReactDOM.findDOMNode(this.refs.codeNumber).onclick){
    //         alert("1111111111111111111111111111");
    //     }
    // }
}
login.propTypes = {
    isFetching: PropTypes.bool.isRequired,
    dispatch: PropTypes.func.isRequired
};
login.contextTypes = {
    router: React.PropTypes.object
};
function mapStateToProps(state) {
    const {postsByApi} = state;
    const {
        isFetching,
        items: ValidateCode
    } = postsByApi["sendValidateCodeToPhone"] || {
        isFetching: false,
        items: {}
    };
    const {
        items: VerificationCode
    } = postsByApi["verificationCode"] || {
        items: {}
    };
    return {
        isFetching,
        ValidateCode,
        VerificationCode
    };
}

export default connect(mapStateToProps)(login);